import KoaRouter from 'koa-router'
import { Models } from '../../../../../common/typings/model'
import { Api } from '../../../../../common/typings/api'
import emailSchema from '../../../../../common/apiValidate/system/user/send/email'
import validator from '../../../../../middlewares/validator'
import sedEmail from '../../../../../common/utils/email'
import { Success } from '../../../../../core/HttpException'
import Auth from '../../../../../middlewares/Auth'
import Config from '../../../../../config/Config'

const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/auth`,
})

/**
 * 邮箱注册，注册成功后，权限为NoVerifyEmail，并发送验证邮件，验证通过后权限为User
 */
router.post('/email', validator(emailSchema, 'body'), async (ctx: Models.Ctx) => {
  const query: Api.User.Register.emailRegister = ctx.request.body as unknown as Api.User.Register.emailRegister
  const validateStatus = await Auth.verifyUserNameExistence(query.userName)
  if (validateStatus) {
    throw new Success('', '该用户名已存在', 200, 1)
  }
  const code = (Math.random() * 1000000).toFixed()
  ctx.session!.code = code
  // 发送邮件
  await sedEmail({
    from: '"FHTWL" <1121145488@qq.com>',
    to: query.email,
    subject: '验证码',
    text: '验证码',
    html: `
            <div >
                <p>您正在注册FHTWL低代码平台帐号，用户名<b>${query.userName}</b>，
                验证邮箱为<b>${query.email}</b> 。
                验证码为：</p>
                <p style="color: green;font-weight: 600;margin: 0 6px;text-align: center; font-size: 20px">
                  ${code}
                </p>
                <p>请在注册页面填写该改验证码</p>
            </div>
        `,
  })

  throw new Success()
})

export default router
